import 'package:aichat_flutter_wallet/module_common/widgets/dialog/easyloading.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';
import 'package:aichat_flutter_wallet/module_common/mpc_help/createWalletTool.dart';
import '../../../../module_common/provider/wallet_info_provider.dart';
import '../assets_network_widget.dart';

class SelectChainListPage extends StatefulWidget {
  final Wallet wallet;
  final ChainType? chainType;
  final bool popChain;

  const SelectChainListPage({super.key, required this.wallet, this.chainType, this.popChain = false});

  @override
  State<StatefulWidget> createState() {
    return _SelectChainListState();
  }
}

class _SelectChainListState extends State<SelectChainListPage> {
  final List<Chain> _chains = [];

  @override
  void initState() {
    super.initState();
    List<WalletInfo> infos = ObjectBox().walletInfoModel.getWalletInfoListByWalletId(widget.wallet.id);
    for (var w in infos) {
      Chain? c = w.getChain();
      if (null != c && !_chains.contains(c)) {
        _chains.add(c);
      }
    }
  }

  void _selectChain(Chain chain) {
    if (widget.popChain) {
      Navigator.of(context).pop([chain]);
      return;
    }

    if (context.read<WalletInfoNotifier>().walletChainShortName == chain.shortName) {
      Navigator.of(context).pop();
      return;
    }

    int walletId = context.read<WalletInfoNotifier>().walletId;
    WalletInfo? info = ObjectBox().walletInfoModel.getWalletInfoByWalletIdAndChain(walletId, chain.shortName);
    if (null != info) {
      context.read<WalletInfoNotifier>().updateCurrentWallet(info);
      Navigator.of(context).pop();
    } else {
      Wallet? currentWallet = context.read<WalletInfoNotifier>().wallet;
      if (currentWallet == null) {
        return;
      }
      EasyLoading.generateLoadingFuture(createWalletTool().createWalletInfo(currentWallet, chain), status: 'loading...')
          .then((value) {
        context.read<WalletInfoNotifier>().updateCurrentWallet(value);
        Navigator.of(context).pop();
      });
    }
  }

  bool _isSelected(Chain chain) {
    return !widget.popChain && context.read<WalletInfoNotifier>().walletChainShortName == chain.shortName;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: PageHeaderCom(
          title: 'Network Management',
        ),
        body: ListView.builder(
            itemCount: _chains.length,
            shrinkWrap: false,
            itemBuilder: (BuildContext context, int index) {
              Chain chain = _chains[index];
              return Stack(
                children: [
                  InkWell(
                    onTap: () {
                      _selectChain(chain);
                    },
                    child: Container(
                      padding:  EdgeInsets.only(left: 20.w, right: 20.w),
                      height: 60.w,
                      color: _isSelected(chain) ? Color.fromRGBO(246, 246, 246, 1) : Colors.transparent,
                      child: Row(
                        children: [
                          ClipRRect(
                              borderRadius: BorderRadius.circular(40),
                              child: PublicImage(
                                image: chain.logo,
                                width: 40.w,
                                height: 40.w,
                              )),
                           SizedBox(
                            width: 10.w,
                            height: 0,
                          ),
                          Expanded(
                              child: Text(
                            chain.name,
                            maxLines: 1,
                            overflow: TextOverflow.clip,
                            style: TextStyle(
                                color: Color.fromRGBO(51, 51, 51, 1), fontSize: 14.sp, fontWeight: FontWeight.w500),
                          )),
                          Visibility(
                              visible: _isSelected(chain),
                              child: SizedBox(
                                  width: 24.w,
                                  height: 24.w,
                                  child: Image.asset('assets/images/wallet_assets/network_selected.png'))),
                          SizedBox(
                            width: 55.w,
                          ),
                        ],
                      ),
                    ),
                  ),
                  Positioned(
                      top: 0,
                      right: 20.w,
                      child: GestureDetector(
                        onTap: () {
                          // Navigator.push(
                          //   context,
                          //   MaterialPageRoute(builder: (context) => WalletSetNode(chain: chain),
                          //       settings: RouteSettings(name: Routes.walletSetNode)
                          //   ),
                          // ).then((value) =>  Navigator.pop(context));
                        },
                        child: Container(
                          width: 50.w,
                          height: 60.w,
                          alignment: Alignment.centerRight,
                          color: Colors.transparent,
                          child: AssetsNodeNetworkWidget(
                            chain: chain,
                            isRepeat: false,
                            onClick: () {},
                          ),
                        ),
                      ))
                ],
              );
            }));
  }
}
